package com.yogee.topseller.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.model.bean.InterestLabelBean;
import com.yogee.topseller.adapter.InterestLabelAdapter;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.bean.SearchKeyBean;
import com.yogee.topseller.bean.SearchPageBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.view.FlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索
 *
 * @auathor ${XiaoJianghong}
 * @date 2017/7/16.
 */

public class SearchActivity extends HttpActivity implements TextView.OnEditorActionListener, FlowLayout.OnLableClickListener {
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_fl_layout)
    FlowLayout flLayout;
    @BindView(R.id.search_history_lable_ll)
    LinearLayout searchHistoryLableLl;
    @BindView(R.id.search_history_ll)
    LinearLayout searchHistoryLl;
    @BindView(R.id.search_hotlable_ll)
    LinearLayout searchHotlableLl;
    @BindView(R.id.search_sv)
    ScrollView searchSv;
    @BindView(R.id.search_lable_ll)
    LinearLayout lableLl;
    @BindView(R.id.search_cancle_tv)
    TextView cancleTv;
    @BindView(R.id.search_lable_rv)
    RecyclerView lableRv;
    @BindView(R.id.search_fastquery_lable_ll)
    LinearLayout fastQueryLl;

    private InterestLabelAdapter mAdapter;
    private List<InterestLabelBean.ListBean> lableBeen;
    private boolean isLable = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
}

    @Override
    protected void initView() {
        searchEt.setOnEditorActionListener(this);
        searchEt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        lableRv.setLayoutManager(new LinearLayoutManager(this));
        lableRv.setHasFixedSize(true);
        mAdapter = new InterestLabelAdapter(this);
        lableRv.setAdapter(mAdapter);
        searchFilter();
        flLayout.setOnLableClickListener(this);

//        loadSearchKey();
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
//        mImmersionBar.statusBarView(R.id.top_view)
//                .statusBarColor(R.color.home_title_color)
////                .navigationBarColor(R.color.btn8)
//                .init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("搜索界面"); //手动统计页面("SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this); //统计时长
        searchPage(AppUtil.getUserId(this));

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("搜索界面"); //手动统计页面("SplashScreen"为页面名称，可自定义)，必须保证 onPageEnd 在 onPause 之前调用，因为SDK会在 onPause 中保存onPageEnd统计到的页面数据。
        MobclickAgent.onPause(this);
    }

    @OnClick({R.id.search_lable_iv, R.id.search_delete_iv, R.id.search_cancle_tv, R.id.search_lable_reset_tv, R.id.search_lable_sure_tv, R.id.search_clean_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_lable_iv://标签
//                searchSv.setVisibility(View.GONE);
//                lableLl.setVisibility(View.VISIBLE);
//                isLable = true;
                startActivity(new Intent(SearchActivity.this,SearchByConditionsActivity.class));
                break;
            case R.id.search_delete_iv://删除
                searchEt.setText("");
                break;
            case R.id.search_cancle_tv://取消 or 确定
                if (isLable) {
                    searchSv.setVisibility(View.VISIBLE);
                    lableLl.setVisibility(View.GONE);
                    isLable = false;
                } else {
                    finish();
                }
                break;
            case R.id.search_lable_reset_tv://重置
                mAdapter = new InterestLabelAdapter(this);
                lableRv.setAdapter(mAdapter);
                mAdapter.addData(lableBeen);
                break;
            case R.id.search_lable_sure_tv://确定
                String name = "";
                for (int i = 0; i < mAdapter.getmSelectBean().size(); i++) {
                    if (i == 0) {
                        name += mAdapter.getmSelectBean().get(i).getName();
                    } else {
                        name += " " + mAdapter.getmSelectBean().get(i).getName();
                    }
                }
                searchIndex(name);
                break;
            case R.id.search_clean_rl://清除历史消息
                clearHistory(AppUtil.getUserId(this));
                break;
        }
    }

    private void searchPage(String userid) {
        HttpManager.getInstance().searchPage(userid, "", "").compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<SearchPageBean>() {
            @Override
            public void onNext(SearchPageBean o) {
                searchHistoryLableLl.removeAllViews();
                searchHotlableLl.removeAllViews();
                if (o.getSearchHistory().size() <= 0) {
                    searchHistoryLl.setVisibility(View.GONE);
                } else {
                    searchHistoryLl.setVisibility(View.VISIBLE);
                    for (int i = 0; i < o.getSearchHistory().size(); i++) {
                        View view = LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_search, null);
                        TextView tv = (TextView) view.findViewById(R.id.item_search_tv);
                        final String name = o.getSearchHistory().get(i).getName();
                        tv.setText(o.getSearchHistory().get(i).getName());
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                searchIndex(name);
                            }
                        });
                        searchHistoryLableLl.addView(view);
                    }
                }
                if (o.getFastQuery().size() <= 0) {
                    fastQueryLl.setVisibility(View.GONE);
                } else {
                    for (int i = 0; i < o.getFastQuery().size(); i++) {
                        View view = LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_search, null);
                        TextView tv = (TextView) view.findViewById(R.id.item_search_tv);
                        tv.setText(o.getFastQuery().get(i).getName());
                        final String name = o.getFastQuery().get(i).getName();
                        view.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                searchIndex(name);
                            }
                        });
                        searchHotlableLl.addView(view);
                    }
                }
                List<String> lables = new ArrayList<>();
                flLayout.cleanTag();
                for (int i = 0; i < o.getHotLabel().size(); i++) {
                    lables.add(o.getHotLabel().get(i).getName());
                }
                flLayout.setDefoutDatas1(lables);
            }
        }, this));
    }

    private void clearHistory(String userId) {
        HttpManager.getInstance().clearHistory(userId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                searchPage(AppUtil.getUserId(SearchActivity.this));
            }
        }, this));
    }

    private void searchFilter() {
        HttpManager.getInstance().searchFilter().compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<InterestLabelBean>() {
            @Override
            public void onNext(InterestLabelBean o) {
                lableBeen = o.getList();
                mAdapter.addData(o.getList());
            }
        }, this));
    }

    private void searchIndex(String name) {
        startActivity(new Intent(SearchActivity.this, SearchResultActivity.class).putExtra("inputText", name).putExtra("type","0"));
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        switch (i) {
            case EditorInfo.IME_ACTION_SEARCH:
                String name = searchEt.getText().toString();

                if (!name.isEmpty()) {
                    searchIndex(name);
                }else{
                     ToastUtils.showToast(SearchActivity.this,"请输入检索信息");
                }
                break;
        }
        return false;
    }

    @Override
    public void onLableClick(String s) {
        searchIndex(s);
    }

    /**
     * 获取搜索关键词
     */
    private void loadSearchKey() {
        HttpManager.getInstance().defaultShow().subscribe(new BaseSubscriber(new HttpOnNextListener<SearchKeyBean>() {
            @Override
            public void onNext(SearchKeyBean o) {
                if (o.getContent() != null && !o.getContent().equals("")){
                    searchEt.setText(o.getContent());
                    searchEt.setSelection(o.getContent().length());
                }
            }
        }, this));
    }
}